package com.ljf.spring;

import com.ljf.framework.exception.NotWebContextException;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * SpringMVC相关操作
 */
public class SpringMVCUtil {

	private SpringMVCUtil() {
	}

	/**
	 * 获取当前会话的 RequestAttributes
	 */
	public static RequestAttributes getRequestAttributes() {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return servletRequestAttributes;
	}

	/**
	 * 获取当前会话的 request
	 * @return request
	 */
	public static HttpServletRequest getRequest() {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if(servletRequestAttributes == null) {
			throw new NotWebContextException("非Web上下文无法获取Request");
		}
		return servletRequestAttributes.getRequest();
	}

	/**
	 * 获取当前会话的 response
	 * @return response
	 */
	public static HttpServletResponse getResponse() {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if(servletRequestAttributes == null) {
			throw new NotWebContextException("非Web上下文无法获取Response");
		}
		return servletRequestAttributes.getResponse();
	}

	/**
	 * 判断当前是否处于 Web 上下文中
	 * @return request
	 */
	public static boolean isWeb() {
		return RequestContextHolder.getRequestAttributes() != null;
	}

	/**
	 * 同步山下文
	 * @param object
	 */
	public static void syncContext(Object object) {
		RequestContextHolder.setRequestAttributes((RequestAttributes) object);
	}

	/**
	 * 获取同步对象
	 * @return
	 */
	public static Object getSyncObject() {
		return RequestContextHolder.getRequestAttributes();
	}
}
